import { serviceUpToken } from '@/api/service'
const qiniu = require('qiniu-js')

/**
 *
 * @param {*} a_file    // 上传的文件
 * @param {*} a_key     // 文件名
 * @param {*} a_token   // 获取的token
 * @returns
 */
export function qiniuUpload(a_file, a_key, a_token) {
  const self = this
  const putExtra = {
    fname: a_key
  }
  const config = {
    useCdnDomain: true,
    region: qiniu.region.z2
  }
  const observable = qiniu.upload(a_file, a_key, a_token, putExtra, config)
  return observable
}

/**
   *
   * @param {*} a_file  // 图片文件
   * @param {*} a_successCB    // 回调函数
   * @param {*} a_complateCB    // 回调函数
   * @param {*} a_errorCB    // 回调函数
   */
export async function uploadForQiniu(a_file, a_successCB, a_complateCB, a_errorCB ) {
  console.log(a_file);
  let file_arr = a_file.name.split('.')
  
  let key = file_arr[0] + '_' + new Date().getTime();
  if(file_arr.length >=2){
    key += `.${file_arr[file_arr.length - 1]}`
  }
  const data = {
    key: key,
  }
  // let subscription = null;
  const res = await serviceUpToken(data)
  const observable = qiniuUpload(a_file.raw, key, res.data.upToken)
  const subscription = observable.subscribe(
    (v) => {console.log('uploadv',v),a_complateCB(v)},
    (err) => {a_errorCB(err)},
    (suc) => {a_successCB(suc)}
  )
  return { observable, key, subscription }
}

/**
   *
   * @param {string} a_videoType // 判断是否为视频文件
   * return 1 是  0 否
   */
function isVideo(a_videoType) {
  //   let video_arr=['avi','mkv','flv','vob','mp4','m4v','mov','3gp','swf','rm','ram','mpg','mpeg','wmv']
  const video_arr = ['avi', 'mp4', 'flv', 'wmv']
  if (video_arr.includes(a_videoType)) {
    return 1
  } else {
    return 0
  }
}

export function isAvart(a_Type) {
  //   let video_arr=['avi','mkv','flv','vob','mp4','m4v','mov','3gp','swf','rm','ram','mpg','mpeg','wmv']
  const Avart_arr = ['png', 'jpg']
  if (Avart_arr.includes(a_Type)) {
    return 1
  } else {
    return 0
  }
}
